package com.it.rocketmp.producer.sender;

import com.it.rocketmp.producer.msg.Msg;
import com.it.rocketmp.producer.msg.Topic;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 发送服务
 */
@Component
public class SenderService {
    private static final String TX_PRODUCER_GROUP = "tx-producer-group";
    /**
     * 注入rocketMq
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 同步发送
     * @param data
     * @return
     */
    public SendResult syncSend(String data) {
        // 创建 Demo01Message 消息
        Msg message = new Msg();
        message.setData(data);
        // 同步发送消息
        return rocketMQTemplate.syncSend(Topic.topic, message);
    }
    /**
     * 异步发送
     * @param data
     * @return
     */
    public void asyncSend(String data, SendCallback callback) {
        // 创建 Demo01Message 消息
        Msg message = new Msg();
        message.setData(data);
        // 同步发送消息
         rocketMQTemplate.asyncSend(Topic.topic, message,callback );
    }
    /**
     * 事务发送
     * @param data
     * @return
     */
    public void asyncSendTransaction(String data, SendCallback callback, Integer id) {
        // 创建 Demo01Message 消息
        Msg msg =    new Msg();
        msg.setData(data);
        msg.setId(id);
        Message<Msg> message = MessageBuilder.withPayload(msg).build();
        // 同步发送消息
        rocketMQTemplate.sendMessageInTransaction(TX_PRODUCER_GROUP,Topic.topic, message,message );
    }
}
